/**
 * @Description: 消费记录
 * @author tao.xie
 * @date $
 */

import React, { Component } from 'react'
import { StyleSheet, View, Text } from 'react-native'
import getCustomRecordList from '../api/CustomRecordApi.js'
import RefreshListView, { RefreshState } from 'react-native-refresh-list-view'
import CustomTradeItem from '../components/customtrade/CustomTradeItem.js'

export default class CustomRecordList extends Component {
  static navigationOptions = () => {
    return {
      headerTitle: '消费记录'
    }
  }

  constructor (props) {
    super(props)

    this.state = {
      cardno: props.navigation.getParam('cardno'),
      pageIndex: 1,
      pageCapcity: 10,
      dataList: [],
      refreshState: RefreshState.Idle
    }
  }

  componentDidMount (): void {
    this.onHeaderRefresh()
  }

  renderCell = ({ item }) => {
    return <CustomTradeItem item={item}/>
  }

  onHeaderRefresh = () => {
    this.setState({ refreshState: RefreshState.HeaderRefreshing, pageIndex: 1 }, () => {
      this.calRefreshState()
    })
  }

  onFooterRefresh = () => {
    this.setState({ refreshState: RefreshState.FooterRefreshing, pageIndex: this.state.pageIndex + 1 }, () => {
      this.calRefreshState()
    })
  }

  calRefreshState = async () => {
    let tradeDetailList = await getCustomRecordList(this.state.cardno, this.state.pageIndex, this.state.pageCapcity)
    let [count, dataList] = [tradeDetailList.COUNT, tradeDetailList.LIST]
    let detailCount = 0
    dataList.map(item => {
      detailCount += item.tradeDetails.length
    })

    if (count === 0) {
      // 总数为0，空数据
      this.setState({ refreshState: RefreshState.EmptyData })
    } else {
      let loadedItemCount = (this.state.pageIndex - 1) * this.state.pageCapcity
      let resetItemCount = count - loadedItemCount

      this.setState({
        dataList: this.state.pageIndex === 1 ? [].concat(dataList) : [...this.state.dataList, ...dataList],
        refreshState: resetItemCount === detailCount ? RefreshState.NoMoreData : RefreshState.Idle
      })
    }
  }

  render () {
    return (
      <View style={styles.container}>
        <RefreshListView data={this.state.dataList} keyExtractor={(item, index) => index + ''}
          renderItem={this.renderCell}
          refreshState={this.state.refreshState}
          onHeaderRefresh={this.onHeaderRefresh}
          onFooterRefresh={this.onFooterRefresh}/>
      </View>
    )
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1
  }
})